<?php
/**
 * Created by PhpStorm.
 * User: YAN
 * Date: 2017/6/30
 * Time: 11:26
 */

namespace App\Http\Controllers\API;


use App\Components\LoginService;
use App\Http\Controllers\Controller;
use App\Models\AdminLog;
use App\Models\User;
use App\Models\UserInfo;
use App\Http\Requests\AdminRequest as Request;
use App\Models\UserWechat;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class BackgroundUserController extends Controller
{
    public function getUserByToken($token){
        $user = User::query()->where(['api_token'=>$token])->first();
        if(empty($user)){
//            Auth::logout();
            $result = false;
        }else{
            $user_info = $this->findInfo($user->id);
            $result = array_merge($user->toArray(),$user_info->toArray());
        }

        return $result;
    }
    public function getUserPermissions($token){
        $user = User::query()->where(['api_token'=>$token])->first();
        if($user){
            $roles = DB::table('user_role')->Where(['user_role.user_id'=>$user->id])
                ->join('role_permission', 'role_permission.role_id', '=', 'user_role.role_id')
                ->join('permissions', 'role_permission.permission_id', '=', 'permissions.id')
                ->pluck('permissions.slug')->toArray();
            return array_unique($roles);
        }else{
            return response(false, 406);
        }


    }
    public function loginService(Request $request){
        $username = $request->get('username');
        $pwd = $request->get('pwd');
        $login = new LoginService();
        return $login->getUserByCode($username,$pwd);
    }
    public function index(Request $request)
    {
        $queryString = $request->get('query', '');
        $models = User::query()
            ->where('name', 'like', '%' . $queryString . '%')
            ->paginate();
        return $models;
    }


    /**
     * 添加员工
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new User();
        $model->fill($request->all());
        $model->password = bcrypt($model->password);
        $model->api_token = str_random(60);
        $logs = new AdminLog();
        $logs->admin = Auth::user()->id;
        $logs->logs = '新增后台工作人员：'.$model->name;
        if (!$logs->save()) {
            throw new \Exception('记录保存失败');
        }
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 修改员工
     * @param User $User
     * @param Request $request
     * @return mixed
     */
    public function update(User $user, Request $request)
    {
        DB::table('user_role')->where('user_id',$user->id)->delete();
        $role = $request->get('role');
        $wechat = $request->get('wechat');
        $info=$this->findInfo($user->id);
        $user->attachRoles($role);
        $info->u_id=$user->id;
        $info->fill($request->all());
        if($wechat){
            UserWechat::query()->where(['user_id'=>$user->id])->delete();
            foreach ($wechat as $item){
                $log =  new UserWechat();
                $log->user_id = $user->id;
                $log->wechat_id = $item;
                $log->save();
            }
        }
        $logs = new AdminLog();
        $logs->admin = Auth::user()->id;
        $logs->logs = '修改后台工作人员信息：'.$user->name;
        if (!$logs->save()) {
            throw new \Exception('记录保存失败');
        }
        if ($info->save()) {
            return $user;
        } else {
            return response($info->getErrors()->toArray(), 406);
        }
    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $logs = new AdminLog();
            $logs->admin = Auth::user()->id;
            $logs->logs = '删除后台工作人员信息：'. $model->name;
            if (!$logs->save()) {
                throw new \Exception('记录保存失败');
            }
            $model->delete();
            UserInfo::query()->where(['u_id'=>$id])->delete();
            return ['state' => 'success'];
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show($id)
    {
        $user=$this->findModel($id);
        $info= $this->findInfo($id);
        $result['id'] = $user->id;
        $result['role'] = $user->role;
        $result['wechat'] = $user->wechat;
        $result['name']= $info->name;
        $result['email']= $user->email;
        $result['mobile']=$info->mobile;
        $result['gender']=$info->gender;
        $result['political_outlook']=$info->political_outlook;
        $result['desc']=$info->desc;
        return $result;
    }




    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = User::find($id);
        return $model;
    }
    private function findInfo($id){
        $model = UserInfo::query()->where(['u_id'=>$id])->first();
        if(!$model){
            $model = new UserInfo();
        }
        return $model;
    }


}